(function () {

  window.trochiliUM = [];

  var handleEditor = function (editorId) {

    var _UM = UM.getEditor(editorId, {
      toolbar: [
        'bold italic underline insertorderedlist insertunorderedlist image video insertcode'
      ],
    });

    window.trochiliUM.push(_UM);

    var $editor = $('#' + editorId);

    var allowTags = ['font', 'embed', 'a', 'img', 'br', 'strong', 'b', 'code', 'pre', 'p', 'div', 'em', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'table', 'tr', 'th', 'td', 'hr', 'ul', 'ol', 'li', 'u', 'i', 'dl', 'dt', 'dd'];
    var allowAttributes = ['size', 'loop', 'title', 'value', 'type', 'name', 'size', 'target', , 'src', 'href', 'alt', 'width', 'height', 'rel', 'tabindex'];

    // 移除非法 html 属性
    var removeNotAllowAttributes = function (cb) {
      $editor.find('*').each(function () {
        var $tag = $(this);
        $.each($tag.get(0).attributes, function () {
          if (allowAttributes.indexOf(this.name) === -1) {
            $tag.attr(this.name, '');
          }
        });
      });
      cb && cb();
    };

    // 替换非法 html 标签为 p 标签
    var replaceNotAllowTags = function () {
      $editor.find('*').each(function () {
        var $tag = $(this);
        if (allowTags.indexOf($tag.get(0).tagName.toLowerCase()) === -1) {
          $tag.replaceWith('<p>' + $tag.html() + '</p>');
        }
      });
    };

    _UM.addListener('contentChange', function () {
      removeNotAllowAttributes(function () {
        replaceNotAllowTags();
      });
    });

  };

  handleEditor('editor');

})();
